package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
)

func main() {
	address := "127.0.0.1:9999"
	conn, err := net.Dial("tcp", address)
	if err != nil {
		fmt.Printf("客户端创建连接失败\n")
		return
	}
	for {
		//从命令行读取数据 发给服务器
		reader := bufio.NewReader(os.Stdin)
		data, err2 := reader.ReadString('\n')
		data = strings.Trim(data, "\n")
		if err2 != nil {
			return
		}
		if data == "" {
			continue
		}
		if data == "quit" || data == "q" || data == "exit" {
			break
		}
		i, err := conn.Write([]byte(data))
		if err != nil {
			fmt.Printf("发送给服务端失败, err=%v\n", err)
			return
		}
		//从服务器读取数据 写入到标准输出
		var serverData = make([]byte, 1024)
		i, err = conn.Read(serverData)
		if err != nil {
			fmt.Printf("接收服务端返回失败, err=%v\n", err)
			return
		}
		fmt.Println(strings.Trim(string(serverData[:i]), "\n"))
	}
	fmt.Println("退出客户端")
}
